<template>
  <el-card>
    <div class="header">
      <h3>用户体验反馈</h3>
      <el-button type="primary" @click="handleRefresh">刷新</el-button>
    </div>
    
    <el-table :data="feedbacks" style="width: 100%" v-loading="loading">

      <el-table-column label="编号" type="index" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="content" label="反馈内容" show-overflow-tooltip />
      <el-table-column prop="contact" label="联系方式" width="150" />
      <el-table-column prop="createTime" label="提交时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary" 
            @click="handleResponse(scope.row)"
            :disabled="scope.row.status === 1"
          >
            处理
          </el-button>
          <el-button 
            size="small" 
            type="info" 
            @click="handleViewDetail(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="反馈详情"
      width="60%"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="反馈内容" :span="2">
          {{ detailData.content }}
        </el-descriptions-item>
        <el-descriptions-item label="提交时间">
          {{ formatDate(detailData.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="用户ID">
          {{ detailData.userId }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ detailData.username }}
        </el-descriptions-item>
        <el-descriptions-item label="联系方式">
          {{ detailData.contact }}
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 处理记录部分 -->
      <div v-if="detailData.responses && detailData.responses.length > 0" class="response-section">
        <h4>处理记录</h4>
        <el-timeline>
          <el-timeline-item
            v-for="response in detailData.responses"
            :key="response.responseId"
            :timestamp="formatDate(response.createTime)"
            :type="getResponseTypeColor(response.responseType)"
          >
            <h4>{{ getResponseTypeText(response.responseType) }}</h4>
            <p>处理人：{{ response.adminName }}</p>
            <p>回复内容：{{ response.responseContent }}</p>
            <p v-if="response.actionTaken">采取措施：{{ response.actionTaken }}</p>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 处理反馈对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="处理反馈"
      width="50%"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form :model="responseForm" label-width="100px">
        <el-form-item label="反馈内容">
          <div class="feedback-content">{{ currentFeedback?.content }}</div>
        </el-form-item>
        <el-form-item label="回复内容" required>
          <el-input
            v-model="responseForm.response_content"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
        <el-form-item label="处理类型" required>
          <el-select v-model="responseForm.response_type" placeholder="请选择处理类型">
            <el-option label="确认修正" :value="1" />
            <el-option label="无需修正" :value="2" />
            <el-option label="待确认" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="采取措施">
          <el-input
            v-model="responseForm.action_taken"
            type="textarea"
            :rows="2"
            placeholder="请输入采取的措施"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResponse">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'FeedbackExperience',
  
  data() {
    return {
      loading: false,
      feedbacks: [],
      dialogVisible: false,
      detailDialogVisible: false,
      currentFeedback: null,
      detailData: {},
      responseForm: {
        response_content: '',
        response_contact: '',
        response_type: 1,
        action_taken: ''
      },
      // 添加分页相关数据
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },

  methods: {
    async fetchFeedbacks() {
      this.loading = true
      try {
        // 使用FeedbackVOController的list接口获取数据
        const response = await this.$http.get("http://localhost:8080/feedback-vo/list")
        console.log('反馈列表数据:', response.data)
        
        // 检查返回的数据格式
        let dataArray = []
        if (Array.isArray(response.data)) {
          dataArray = response.data
        } else if (response.data && typeof response.data === 'object') {
          dataArray = response.data.content || response.data.data || response.data.list || []
        }

        // 过滤用户体验反馈（feedbackType === 1）
        const filteredData = dataArray.filter(item => item.feedbackType === 1)
        
        // 设置总数（使用过滤后的数据长度）
        this.total = filteredData.length
        console.log('过滤后的数据总数:', this.total)
        
        // 计算当前页的数据
        const start = (this.currentPage - 1) * this.pageSize
        const end = start + this.pageSize
        const pageData = filteredData.slice(start, end)
        console.log('当前页数据范围:', start, '到', end)
        console.log('当前页数据条数:', pageData.length)

        this.feedbacks = pageData.map(item => ({
          feedbackId: item.feedbackId,
          userId: item.userId,
          username: item.username || '',
          content: item.content || '',
          contact: item.contact || '',
          createTime: item.createTime,
          status: item.status || 0,
          courseId: item.courseId,
          courseName: item.courseName || ''
        }))
        
        if (this.feedbacks.length === 0) {
          ElMessage.info('暂无用户体验反馈数据')
        }
      } catch (error) {
        ElMessage.error('获取反馈列表失败')
        console.error('Error fetching feedbacks:', error)
        this.feedbacks = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 添加分页处理方法
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1 // 重置到第一页
      this.fetchFeedbacks()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchFeedbacks()
    },
    
    async handleViewDetail(row) {
      try {
        const response = await this.$http.get(`http://localhost:8080/feedback-vo/detail/${row.feedbackId}`)
        this.detailData = {
          feedbackId: response.data.feedbackId,
          userId: response.data.userId || '',
          username: response.data.username || '',
          content: response.data.content || '',
          contact: response.data.contact || '',
          createTime: response.data.createTime,
          status: response.data.status || 0,
          courseName: response.data.courseName || '',
          responses: response.data.responses || []
        }
        this.detailDialogVisible = true
      } catch (error) {
        ElMessage.error('获取详情失败')
        console.error(error)
      }
    },

    getResponseTypeColor(type) {
      const colors = {
        1: 'success',
        2: 'info',
        3: 'warning'
      }
      return colors[type] || 'info'
    },

    getResponseTypeText(type) {
      const types = {
        1: '确认修正',
        2: '无需修正',
        3: '待确认'
      }
      return types[type] || '未知'
    },

    handleResponse(row) {
      this.currentFeedback = row
      this.dialogVisible = true
    },

    async submitResponse() {
      if (!this.responseForm.response_content) {
        ElMessage.warning('请输入回复内容')
        return
      }

      // 检查currentFeedback对象
      console.log('当前反馈对象:', this.currentFeedback)
      if (!this.currentFeedback || !this.currentFeedback.feedbackId) {
        ElMessage.error('反馈ID不存在')
        return
      }

      try {
        // 1. 添加回复记录
        const responseData = {
          feedbackId: Number(this.currentFeedback.feedbackId),
          adminId: 1,
          responseType: this.responseForm.response_type,
          responseContent: this.responseForm.response_content,
          createTime: new Date().toISOString(),
          status: 1,
          feedbackType: 1,
          actionTaken: this.responseForm.action_taken || '',
          beforeContent: '',
          afterContent: ''
        }

        console.log('提交的回复数据:', responseData)

        const response = await this.$http.post('http://localhost:8080/feedback_responses/add', responseData, {
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (!response.data) {
          throw new Error('添加回复记录失败')
        }

        // 2. 更新用户反馈表的状态
        const updateData = {
          ...this.currentFeedback,
          feedbackType: this.currentFeedback.feedbackType ?? 1, // 如果没有就补1
          status: 1
        }

        console.log('更新反馈数据:', updateData)
        await this.$http.put('http://localhost:8080/feedbacks/update', updateData)

        ElMessage.success('回复成功')
        this.dialogVisible = false
        this.fetchFeedbacks()
      } catch (error) {
        console.error('提交回复失败:', error)
        if (error.response) {
          console.error('错误响应:', error.response.data)
        }
        ElMessage.error(error.response?.data?.message || error.message || '回复失败')
      }
    },

    handleRefresh() {
      this.fetchFeedbacks()
    },

    formatDate(date) {
      if (!date) return ''
      try {
        const dateStr = date.toString()
        if (dateStr.includes('T')) {
          const d = new Date(dateStr)
          if (isNaN(d.getTime())) {
            return ''
          }
          return d.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          })
        }
        return dateStr
      } catch (error) {
        console.error('日期格式化错误:', error)
        return ''
      }
    },

    getStatusType(status) {
      const types = {
        0: 'warning',
        1: 'success',
        2: 'info'
      }
      return types[status] || 'info'
    },

    getStatusText(status) {
      const texts = {
        0: '待处理',
        1: '已处理',
        2: '已关闭'
      }
      return texts[status] || '未知'
    }
  },

  mounted() {
    this.fetchFeedbacks()
  }
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.response-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.response-section h4 {
  margin-bottom: 15px;
  color: #606266;
}

.feedback-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.el-card:hover{
  box-shadow: 0 4px 19px rgba(0, 0, 0, 0.25);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>